<template>
  <div class="new-table-style">
    <el-table :border="true" :data="tableData" align="left">
      <el-table-column label="收款金额(元)">
        <template slot-scope="scope">
          <span>{{ scope.row.receivedAmount | fmoneyThousand }}</span>
        </template>
      </el-table-column>
      <el-table-column label="流水号" prop="serialNumber"></el-table-column>
      <el-table-column label="付款方" prop="payer"></el-table-column>
      <el-table-column label="付款账号" prop="paymentAccount"></el-table-column>
      <el-table-column label="付款银行" prop="paymentBank"></el-table-column>
      <el-table-column label="收款时间">
        <template slot-scope="scope">
          <span>{{ scope.row.collectionTime | dateFormat('YYYY-MM-DD') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="description"></el-table-column>
      <el-table-column label="已核销金额(元)">
        <template slot-scope="scope">
          <span>{{ scope.row.writeOffAmount | fmoneyThousand }}</span>
        </template>
      </el-table-column>
      <el-table-column label="剩余金额(元)">
        <template slot-scope="scope">
          <span>{{ scope.row.surplusAmount | fmoneyThousand }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="doWriteOff(scope.row)">核销</el-button>
        </template>
      </el-table-column>
    </el-table>
    <Pagination v-if="total > 0" @change="pageChange" :total="total" paginationLayout="total, prev, pager, next" />

    <div class="absolute-box btn-box flex">
      <el-button v-if="activeTab == '1'" type="primary" size="mini" @click="uploadLoad">下载模板</el-button>
      <el-upload v-if="activeTab == '1'" :show-file-list="false" style="padding: 0 10px" class="upload-demo" action accept="" :http-request="event => beforeupload(event.file)">
        <el-button type="primary" size="mini">导入</el-button>
      </el-upload>
      <el-button type="primary" size="mini" @click="exportFn">导出</el-button>
    </div>

    <el-dialog :visible.sync="dialogShow" width="90%" :close-on-click-modal="false" :close-on-press-escape="false">
      <div slot="title">
        <div>
          <span class="font-size-18 font-weight-700">核销</span>
          <span class="font-size-14 padding-left-20">可核销金额{{ currentBill.surplusAmount }}元</span>
        </div>
      </div>

      <template v-if="writeOffList.length > 0">
        <div v-for="(item, index) in writeOffList" :key="item.guid" class="padding-bottom-10 fill-box relative-box" :class="index < writeOffList.length - 1 ? 'border-b-line margin-bottom-30' : ''">
          <form-common :filed-list="item.filedList" :ref="`writeOff${index}`" @selectChange="selectChange"></form-common>
          <el-button class="delete-btn" type="danger" size="mini" @click="deleteWriteOff(index)">删除</el-button>
        </div>
      </template>
      <el-empty v-else description="暂无数据"></el-empty>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" class="el-button-reset" @click="addWriteOf">添加核销信息</el-button>
        <el-button type="primary" size="mini" @click="saveWriteOff">确 认</el-button>
        <el-button size="mini" @click="dialogShow = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import formCommon from '@g/components/form/formCommon.vue';
  import { writeOffFiledList } from '../../../assets/form';
  import { guid, setFiledVal, requestTips, formDataDate, accAdd } from '@/common/js/utils';
  import { apiWriteOffList, apiWriteOff, apiWriteOffImport, apiWriteOffBillImport, apiGetChargeListByContract, apiWriteOffExport } from '../../../api/billManage';

  export default {
    name: 'cashList',
    props: {
      activeTab: {
        type: String,
        default: '',
      },
      options: {
        type: Object,
        default: () => {
          return {};
        },
      },
    },

    watch: {
      options: {
        deep: true,
        handler(obj) {
          this.setOptions();
        },
      },
    },

    data() {
      return {
        dialogShow: false,
        writeOffList: [],
        tableData: [],
        total: 0,
        currentPage: 1,
        pageSize: 10,
        currentBill: {},
        loading: null,
        projectKey: localStorage.getItem('projectKey'),
      };
    },

    methods: {
      init() {
        this.getList();
      },

      //核销
      doWriteOff(row) {
        this.currentBill = row;
        this.dialogShow = true;
        this.writeOffList = [];

        let filedList = this.lodash.cloneDeep(writeOffFiledList);
        this.writeOffList.push({
          guid: guid(),
          filedList: filedList,
        });
      },

      //添加核销信息
      addWriteOf() {
        let filedList = this.lodash.cloneDeep(writeOffFiledList);
        this.writeOffList.push({
          guid: guid(),
          filedList: filedList,
        });
      },

      //确认核销
      async saveWriteOff() {
        let list = [];
        let allAmount = 0;
        if (this.writeOffList.length == 0) {
          this.$message.warning('请添加核销信息!');
          return;
        }

        this.writeOffList.forEach((item, index) => {
          let formName = 'writeOff' + index;
          let model = this.$refs[formName][0].validateForm();
          list.push(model);
        });

        if (list.indexOf(false) > -1) {
          return;
        }

        list.forEach(item => {
          allAmount = accAdd(allAmount, item.writeOffAmount);
        });

        if (allAmount > this.currentBill.surplusAmount) {
          this.$message.warning('核销金额大于可核销金额！');
          return;
        }

        let res = await apiWriteOff({ writeOffList: list, incomeKey: this.currentBill.primaryKey });
        requestTips(res, () => {
          this.dialogShow = false;
          this.getList('');
        });
      },

      //删除核销
      deleteWriteOff(index) {
        this.writeOffList.splice(index, 1);
      },

      //数据源
      async getList(more) {
        let res = await apiWriteOffList({
          currentPage: more ? this.currentPage : 1,
          pageSize: this.pageSize,
          incomeStatus: this.activeTab,
        });
        this.tableData = res.rows || [];
        this.total = res.total || 0;
      },

      //下拉框数据源
      setOptions() {
        console.log(this.options);
        writeOffFiledList.forEach(item => {
          if (item.bindFieldName == 'projectKey') {
            item.optionList = this.options.projectList;
          }
          if (item.bindFieldName == 'bizType') {
            item.optionList = this.options.costTypeList;
          }
          if (item.bindFieldName == 'contractCode') {
            item.optionList = this.options.contractList;
          }
          // if (item.bindFieldName == 'chargeItemCode') {
          //   item.optionList = this.options.assetList;
          // }
        });
      },

      initFiledVal() {
        writeOffFiledList.forEach(item => {
          if (item.bindFieldName == 'projectKey') {
            item.bindFieldVal = this.projectKey;
          }
        });
      },

      //表单事件
      async selectChange(data) {
        //选账单
        if (data.filedName == 'bizType' || data.filedName == 'contractCode' || data.filedName == 'chargeItemCode') {
          if (data.model.projectKey && data.model.contractCode && data.model.bizType && data.model.chargeItemCode) {
            let params = {
              projectKey: data.model.projectKey,
              contractCode: data.model.contractCode,
              bizType: data.model.bizType,
              chargeItemCode: data.model.chargeItemCode,
              paymentStatusList: [1, 2, 3],
            };
            let res = await apiWriteOffBillImport(params);
            res.rows.forEach(item => {
              item.name = formDataDate(item.cycleStartTime) + '至' + formDataDate(item.cycleEndTime) + '账单';
            });
            data.cbList('billKey', res.rows || []);
          }
          if (data.filedName == 'contractCode') {
            let res = await apiGetChargeListByContract({ contractCode: data.filedVal });
            data.cbList('chargeItemCode', res.rows || []); //费用所属
          }
        }
        if (data.filedName == 'billKey') {
          let target = data.formItem.optionList.find(item => item.primaryKey == data.filedVal);
          data.cb('shouldAmount', target.amountReceivable);
          data.cb('alreadyAmount', target.amountReceived);
        }
      },

      //分页
      pageChange(page) {
        this.currentPage = page.currentPage;
        this.getList('more');
      },

      //导入
      beforeupload(file) {
        this.showLoad();
        apiWriteOffImport(file).then(res => {
          this.$message.success('上传成功');
          this.getList('');
          this.loading.close();
        });
      },

      //下载
      uploadLoad() {
        let a = document.createElement('a');
        a.style.display = 'none';
        a.href = '/static/现金核销.xlsx';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      },

      //导出
      exportFn() {
        apiWriteOffExport({
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          incomeStatus: this.activeTab,
        });
      },

      showLoad() {
        this.loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)',
        });
      },
    },

    created() {
      this.initFiledVal();
    },

    components: { formCommon },
  };
</script>

<style lang="scss" scoped>
  .delete-btn {
    position: absolute;
    bottom: 29px;
    right: 0;
  }
  .search-style-box {
    background: #fbfbfb;
    border-radius: 3px;
    padding: 20px 20px 0;
    margin-bottom: 20px;
  }

  .btn-box {
    right: 0;
    top: -45px;
  }
</style>
